package com.dd.controller;

import com.dd.model.PublicSupervisionData;
import com.dd.service.PublicDataService;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.Set;
import java.util.HashSet;
/*`PublicDataListController` 是 JavaFX 应用中的一个控制器类，主要用于“公众监督数据列表”页面的数据展示和交互。它的主要功能包括：

1. **数据显示与表格绑定**：  
   负责将所有公众监督数据（如编号、提交日期、地址、省、市、问题类型、严重程度、状态、指派网格员、预估AQI、反馈人姓名等）加载到 TableView 表格中，并与每一列进行属性绑定。

2. **搜索与筛选**：  
   支持多条件搜索（如按ID、地址、问题类型、日期、状态、严重程度、省、市、网格员、预估AQI、反馈人姓名等），并可通过下拉框筛选省份、城市、状态，实现数据的快速定位和过滤。

3. **统计信息展示**：  
   页面上会显示一些统计数据，比如已检测AQI的数量、涉及的省份数量、城市数量等。

4. **指派与详情查看**：  
   - 可以选中一条数据，点击按钮进入“指派/修改”页面（弹窗），为该数据指派网格员或修改状态。
   - 可以选中一条数据，点击按钮查看该数据的详细信息（弹窗）。

5. **刷新数据**：  
   支持一键刷新，重新加载所有数据并更新筛选器和统计信息。

6. **界面交互**：  
   通过监听输入框、下拉框等控件的变化，实时更新表格内容和统计信息。

---

**总结**：  
这个类就是“公众监督数据列表页面”的控制器，负责加载、展示、筛选、统计、指派和查看公众监督数据，实现数据管理和交互的全部核心逻辑。*/
public class PublicDataListController {

    // FXML 注入 UI 元素
    @FXML
    private TableView<PublicSupervisionData> publicDataTable;
    @FXML
    private TableColumn<PublicSupervisionData, String> idCol;
    @FXML
    private TableColumn<PublicSupervisionData, String> submitDateCol;
    @FXML
    private TableColumn<PublicSupervisionData, String> specificAddressCol;
    @FXML
    private TableColumn<PublicSupervisionData, String> provinceCol;
    @FXML
    private TableColumn<PublicSupervisionData, String> cityCol;
    @FXML
    private TableColumn<PublicSupervisionData, String> problemTypeCol;
    @FXML
    private TableColumn<PublicSupervisionData, String> severityCol;
    @FXML
    private TableColumn<PublicSupervisionData, String> statusCol;
    @FXML
    private TableColumn<PublicSupervisionData, String> assignedWorkerCol;
    @FXML
    private TableColumn<PublicSupervisionData, String> estimatedAqiCol;
    @FXML
    private TableColumn<PublicSupervisionData, String> feedbackerNameCol;

    @FXML
    private TextField searchField;
    @FXML
    private ComboBox<String> searchCategoryComboBox;
    @FXML
    private ComboBox<String> filterProvinceComboBox;
    @FXML
    private ComboBox<String> filterCityComboBox;
    @FXML
    private ComboBox<String> filterStatusComboBox;

    @FXML
    private Label aqiDetectionCountLabel;
    @FXML
    private Label provinceCountLabel;
    @FXML
    private Label cityCountLabel;

    private PublicDataService publicDataService;
    private ObservableList<PublicSupervisionData> masterData;
    private ObservableList<PublicSupervisionData> filteredData;

    public PublicDataListController() {
        publicDataService = new PublicDataService();
    }

    @FXML
    private void initialize() {
        // 设置 TableView 的列与 PublicSupervisionData 属性的映射
        idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
        submitDateCol.setCellValueFactory(new PropertyValueFactory<>("submitDate"));
        specificAddressCol.setCellValueFactory(new PropertyValueFactory<>("specificAddress"));
        provinceCol.setCellValueFactory(new PropertyValueFactory<>("province"));
        cityCol.setCellValueFactory(new PropertyValueFactory<>("city"));
        problemTypeCol.setCellValueFactory(new PropertyValueFactory<>("problemType"));
        severityCol.setCellValueFactory(new PropertyValueFactory<>("severity"));
        statusCol.setCellValueFactory(new PropertyValueFactory<>("status"));
        assignedWorkerCol.setCellValueFactory(new PropertyValueFactory<>("assignedGridWorker"));
        estimatedAqiCol.setCellValueFactory(new PropertyValueFactory<>("estimatedAqi"));
        feedbackerNameCol.setCellValueFactory(new PropertyValueFactory<>("feedbackerName"));

        // 加载初始数据
        loadPublicSupervisionData();

        // 初始化搜索类别下拉框
        searchCategoryComboBox.setItems(FXCollections.observableArrayList(
                "ID", "具体地址", "问题类型", "提交日期", "状态", "严重程度", "省份", "城市", "指派网格员", "预估AQI等级", "反馈人姓名"
        ));
        searchCategoryComboBox.getSelectionModel().selectFirst();

        // 初始化筛选条件下拉框
        populateFilterComboBoxes();

        // 首次加载时应用过滤器，以显示所有数据并初始化统计信息
        applyFilters();
        updateStatisticsLabels();

        // 为搜索框和筛选器添加监听器
        searchField.textProperty().addListener((observable, oldValue, newValue) -> applyFilters());
        searchCategoryComboBox.valueProperty().addListener((observable, oldValue, newValue) -> applyFilters());
    }

    private void loadPublicSupervisionData() {
        masterData = FXCollections.observableArrayList(publicDataService.getAllPublicSupervisionData());
        // 刷新数据时，filteredData也应该基于新的masterData重新初始化
        filteredData = FXCollections.observableArrayList(masterData);
        publicDataTable.setItems(filteredData);
    }

    private void populateFilterComboBoxes() {
        // 获取所有不重复的省份、城市和状态
        Set<String> provinces = new HashSet<>();
        Set<String> cities = new HashSet<>();
        Set<String> statuses = new HashSet<>();

        for (PublicSupervisionData data : masterData) {
            if (data.getProvince() != null && !data.getProvince().isEmpty()) {
                provinces.add(data.getProvince());
            }
            if (data.getCity() != null && !data.getCity().isEmpty()) {
                cities.add(data.getCity());
            }
            if (data.getStatus() != null && !data.getStatus().isEmpty()) {
                statuses.add(data.getStatus());
            }
        }

        // 初始化省份筛选下拉框
        ObservableList<String> provinceOptions = FXCollections.observableArrayList("全部");
        provinceOptions.addAll(provinces.stream().sorted().collect(Collectors.toList()));
        filterProvinceComboBox.setItems(provinceOptions);
        filterProvinceComboBox.getSelectionModel().select("全部"); // 默认选择"全部"
        // 移除旧的监听器，避免重复添加
        filterProvinceComboBox.setOnAction(null);
        filterProvinceComboBox.setOnAction(event -> {
            updateCityFilterComboBox(); // 当省份选择改变时，更新城市下拉框
            applyFilters(); // 应用新的筛选条件
        });

        // 初始化城市筛选下拉框（依赖于省份选择，初始时显示所有城市）
        ObservableList<String> cityOptions = FXCollections.observableArrayList("全部");
        cityOptions.addAll(cities.stream().sorted().collect(Collectors.toList())); // 初始加载所有城市
        filterCityComboBox.setItems(cityOptions);
        filterCityComboBox.getSelectionModel().select("全部"); // 默认选择"全部"
        // 移除旧的监听器，避免重复添加
        filterCityComboBox.setOnAction(null);
        filterCityComboBox.setOnAction(event -> applyFilters());

        // 初始化状态筛选下拉框
        ObservableList<String> statusOptions = FXCollections.observableArrayList("全部");
        statusOptions.addAll(statuses.stream().sorted().collect(Collectors.toList()));
        filterStatusComboBox.setItems(statusOptions);
        filterStatusComboBox.getSelectionModel().select("全部"); // 默认选择"全部"
        // 移除旧的监听器，避免重复添加
        filterStatusComboBox.setOnAction(null);
        filterStatusComboBox.setOnAction(event -> applyFilters());

        // 确保在populateFilterComboBoxes执行后，城市下拉框能够根据当前的省份选择正确更新
        updateCityFilterComboBox();
    }

    // 根据选择的省份动态更新城市列表
    private void updateCityFilterComboBox() {
        String selectedProvince = filterProvinceComboBox.getSelectionModel().getSelectedItem();
        ObservableList<String> citiesForProvince = FXCollections.observableArrayList("全部");

        if (selectedProvince != null && !selectedProvince.equals("全部")) {
            masterData.stream()
                    .filter(data -> selectedProvince.equals(data.getProvince()))
                    .map(PublicSupervisionData::getCity)
                    .filter(Objects::nonNull) // 过滤null值
                    .distinct()
                    .sorted()
                    .forEach(citiesForProvince::add);
        } else {
            // 如果选择了"全部省份"，则显示所有不重复的城市
            masterData.stream()
                    .map(PublicSupervisionData::getCity)
                    .filter(Objects::nonNull) // 过滤null值
                    .distinct()
                    .sorted()
                    .forEach(citiesForProvince::add);
        }
        filterCityComboBox.setItems(citiesForProvince);
        // 如果当前已选城市在新列表中不存在，则重置为"全部"
        if (!citiesForProvince.contains(filterCityComboBox.getSelectionModel().getSelectedItem())) {
            filterCityComboBox.getSelectionModel().select("全部"); // 重置城市选择
        }
    }

    @FXML
    private void handleSearch() {
        applyFilters();
    }

    @FXML
    private void handleResetFilters() {
        searchField.clear();
        searchCategoryComboBox.getSelectionModel().selectFirst();
        filterProvinceComboBox.getSelectionModel().select("全部");
        // 重置城市列表并选择"全部"
        updateCityFilterComboBox();
        filterCityComboBox.getSelectionModel().select("全部");
        filterStatusComboBox.getSelectionModel().select("全部");
        applyFilters();
    }

    private void applyFilters() {
        String searchText = searchField.getText(); // 转换为小写在过滤逻辑内部进行
        String searchCategory = searchCategoryComboBox.getSelectionModel().getSelectedItem();

        // 确保从 ComboBox 获取的值在后续使用中不会是 null
        String selectedProvince = filterProvinceComboBox.getSelectionModel().getSelectedItem() != null ? 
            filterProvinceComboBox.getSelectionModel().getSelectedItem() : "全部";
        String selectedCity = filterCityComboBox.getSelectionModel().getSelectedItem() != null ? 
            filterCityComboBox.getSelectionModel().getSelectedItem() : "全部";
        String selectedStatus = filterStatusComboBox.getSelectionModel().getSelectedItem() != null ? 
            filterStatusComboBox.getSelectionModel().getSelectedItem() : "全部";

        List<PublicSupervisionData> tempFilteredList = masterData.stream()
                .filter(data -> {
                    // 搜索条件过滤
                    boolean matchesSearch = true;
                    if (searchText != null && !searchText.isEmpty()) {
                        String value = "";
                        switch (searchCategory) {
                            case "ID":
                                value = data.getId();
                                break;
                            case "具体地址":
                                value = data.getSpecificAddress();
                                break;
                            case "问题类型":
                                value = data.getProblemType();
                                break;
                            case "提交日期":
                                value = data.getSubmitDate();
                                break;
                            case "状态":
                                value = data.getStatus();
                                break;
                            case "严重程度":
                                value = data.getSeverity();
                                break;
                            case "省份":
                                value = data.getProvince();
                                break;
                            case "城市":
                                value = data.getCity();
                                break;
                            case "指派网格员":
                                value = data.getAssignedGridWorker();
                                break;
                            case "预估AQI等级":
                                value = data.getEstimatedAqi();
                                break;
                            case "反馈人姓名":
                                value = data.getFeedbackerName();
                                break;
                            default:
                                break;
                        }
                        // 使用 Objects.toString() 避免对 null 值调用 toLowerCase()
                        matchesSearch = Objects.toString(value, "").toLowerCase().contains(searchText.toLowerCase());
                    }

                    // 省份过滤 - selectedProvince 现在保证不为 null
                    boolean matchesProvince = "全部".equals(selectedProvince) ||
                            (data.getProvince() != null && selectedProvince.equals(data.getProvince()));

                    // 城市过滤 - selectedCity 现在保证不为 null
                    boolean matchesCity = "全部".equals(selectedCity) ||
                            (data.getCity() != null && selectedCity.equals(data.getCity()));

                    // 状态过滤 - selectedStatus 现在保证不为 null
                    boolean matchesStatus = "全部".equals(selectedStatus) ||
                            (data.getStatus() != null && selectedStatus.equals(data.getStatus()));

                    return matchesSearch && matchesProvince && matchesCity && matchesStatus;
                })
                .collect(Collectors.toList());

        filteredData.setAll(tempFilteredList);
        updateStatisticsLabels();
    }

    private void updateStatisticsLabels() {
        long aqiCount = masterData.stream() // 统计应基于 masterData
                .filter(data -> data.getEstimatedAqi() != null && !data.getEstimatedAqi().isEmpty())
                .count();
        aqiDetectionCountLabel.setText(String.valueOf(aqiCount));

        Set<String> uniqueProvinces = masterData.stream() // 统计应基于 masterData
                .map(PublicSupervisionData::getProvince)
                .filter(p -> p != null && !p.isEmpty())
                .collect(Collectors.toSet());
        provinceCountLabel.setText(String.valueOf(uniqueProvinces.size()));

        Set<String> uniqueCities = masterData.stream() // 统计应基于 masterData
                .map(PublicSupervisionData::getCity)
                .filter(c -> c != null && !c.isEmpty())
                .collect(Collectors.toSet());
        cityCountLabel.setText(String.valueOf(uniqueCities.size()));
    }

    @FXML
    private void handleAssignData() {
        PublicSupervisionData selectedData = publicDataTable.getSelectionModel().getSelectedItem();
        if (selectedData != null) {
            try {
                FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/dd/public_data_assign.fxml"));
                Parent assignRoot = loader.load();

                PublicDataAssignController assignController = loader.getController();
                assignController.setPublicSupervisionData(selectedData);

                Stage assignStage = new Stage();
                assignStage.setTitle("东软环保公众监督系统 - 指派/修改数据");
                assignStage.setScene(new Scene(assignRoot));
                assignStage.initModality(Modality.APPLICATION_MODAL);
                assignStage.initOwner(publicDataTable.getScene().getWindow());
                assignStage.showAndWait();

                // 窗口关闭后刷新数据
                handleRefreshData(); // 调用刷新方法，确保数据更新和界面同步
            } catch (IOException e) {
                e.printStackTrace();
                showAlert(Alert.AlertType.ERROR, "加载错误", "无法加载指派/修改页面。", e.getMessage());
            }
        } else {
            showAlert(Alert.AlertType.WARNING, "未选择", "请选择要指派的数据。");
        }
    }

    @FXML
    private void handleViewDetails() {
        PublicSupervisionData selectedData = publicDataTable.getSelectionModel().getSelectedItem();
        if (selectedData != null) {
            try {
                FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/dd/public_data_details.fxml"));
                Parent detailsRoot = loader.load();

                PublicDataDetailsController detailsController = loader.getController();
                detailsController.setPublicSupervisionData(selectedData);

                Stage detailsStage = new Stage();
                detailsStage.setTitle("东软环保公众监督系统 - 数据详情");
                detailsStage.setScene(new Scene(detailsRoot));
                detailsStage.initModality(Modality.APPLICATION_MODAL);
                detailsStage.initOwner(publicDataTable.getScene().getWindow());
                detailsStage.showAndWait();

            } catch (IOException e) {
                e.printStackTrace();
                showAlert(Alert.AlertType.ERROR, "加载错误", "无法加载数据详情页面。", e.getMessage());
            }
        } else {
            showAlert(Alert.AlertType.WARNING, "未选择", "请选择要查看详情的数据。");
        }
    }

    /**
     * 处理刷新数据按钮点击事件。
     * 重新加载数据，并更新所有筛选器和统计信息。
     */
    @FXML
    private void handleRefreshData() {
        loadPublicSupervisionData();     // 重新加载所有原始数据
        populateFilterComboBoxes();      // 重新填充并初始化筛选器
        applyFilters();                  // 应用当前（或重置后）的筛选条件
        showAlert(Alert.AlertType.INFORMATION, "刷新", "数据已刷新。");
    }

    private void showAlert(Alert.AlertType alertType, String title, String message) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    private void showAlert(Alert.AlertType alertType, String title, String header, String content) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(content);
        alert.showAndWait();
    }
} 